// Copyright Epic Games, Inc. All Rights Reserved.

#pragma once

#include <zencore/iobuffer.h>
#include <zencore/iohash.h>
#include <zenstore/cidstore.h>
#include <zenstore/hashkeyset.h>

#include <memory>

namespace zen {

class GcContext;
class GcManager;
class ScrubContext;

/** CAS storage interface

	This uses the hash of the stored data (after decompression) as the key
  */

class CasStore
{
public:
	virtual ~CasStore() = default;

	inline const CidStoreConfiguration& Config() { return m_Config; }

	struct InsertResult
	{
		bool New = false;
	};

	enum class InsertMode
	{
		kCopyOnly,
		kMayBeMovedInPlace
	};

	virtual void		 Initialize(const CidStoreConfiguration& Config)													   = 0;
	virtual InsertResult InsertChunk(IoBuffer Data, const IoHash& ChunkHash, InsertMode Mode = InsertMode::kMayBeMovedInPlace) = 0;
	virtual std::vector<InsertResult> InsertChunks(std::span<IoBuffer> Data,
												   std::span<IoHash>   ChunkHashes,
												   InsertMode		   Mode = InsertMode::kMayBeMovedInPlace)						   = 0;
	virtual IoBuffer				  FindChunk(const IoHash& ChunkHash)													   = 0;
	virtual bool					  ContainsChunk(const IoHash& ChunkHash)												   = 0;
	virtual void					  FilterChunks(HashKeySet& InOutChunks)													   = 0;
	virtual bool					  IterateChunks(std::span<IoHash>												  DecompressedIds,
													const std::function<bool(size_t Index, const IoBuffer& Payload)>& AsyncCallback,
													WorkerThreadPool*												  OptionalWorkerPool)									   = 0;
	virtual void					  Flush()																				   = 0;
	virtual void					  ScrubStorage(ScrubContext& Ctx)														   = 0;
	virtual void					  GarbageCollect(GcContext& GcCtx)														   = 0;
	virtual CidStoreSize			  TotalSize() const																		   = 0;

protected:
	CidStoreConfiguration m_Config;
	uint64_t			  m_LastScrubTime = 0;
};

ZENCORE_API std::unique_ptr<CasStore> CreateCasStore(GcManager& Gc);

void CAS_forcelink();

}  // namespace zen
